import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
/* Layout */
import Layout from '@/layout';
import { getToken } from '@/utils/auth'; // 导入 getToken 而不是 getAccessToken

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: HomeView,
        name: 'home',
        meta: { requiresAuth: true } // 需要认证
      },
      {
        path: '/check',
        component: () => import('../views/Check.vue'),
        name: 'check',
        meta: { requiresAuth: true } // 需要认证
      },
      {
        path: '/read/:idbook',
        component: () => import('../views/BookView.vue'),
        name: 'read',
        meta: { requiresAuth: true } // 需要认证
      },
      {
        path: '/bookshelf',
        component: () => import('../views/Bookshelf.vue'),
        name: 'bookshelf',
        meta: { requiresAuth: true } // 需要认证
      },
      {
        path: '/chat',
        component: () => import('../views/Chat.vue'),
        name: 'chat',
        meta: { requiresAuth: true } // 需要认证
      },
      {
        path: '/writer',
        component: () => import('../views/WriterCenter.vue'),
        name: 'writer',
        meta: { requiresAuth: true }, // 需要认证
        children: [
          {
            path: '/manage',
            component: () => import('../views/ManageWorks.vue'),
            name: 'manage',
            meta: { requiresAuth: true } // 需要认证
          },
          {
            path: '/create',
            component: () => import('../views/CreateWork.vue'),
            name: 'create',
            meta: { requiresAuth: true } // 需要认证
          }
        ]
      },
      {
        path: '/usercenter',
        component: () => import('../views/UserCenter.vue'),
        name: 'usercenter',
        meta: { requiresAuth: true } // 需要认证
      }
    ]
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false } // 不需要认证
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false } // 不需要认证
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (getToken()) { // 有 token
      next();
    } else { // 无 token
      next('/login');
    }
  } else {
    next(); // 不需要认证的路由正常跳转
  }
});

router.afterEach(() => {
  // 这里可以添加一些在路由跳转后需要执行的代码
});

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err);
};

export default router;
